import numpy as np
from tqdm import tqdm
import os
import sys
import math
from math import *
import cv2
import mmocr.utils as utils
from PIL import Image,ImageDraw,ImageFont
def crop_img(src_img,
             box,
             long_edge_pad_ratio=0.4,
             short_edge_pad_ratio=0.2,
             debug=False):
    """Crop text region with their bounding box.

    Args:
        src_img (np.array): The original image.
        box (list[float | int]): Points of quadrangle.
        long_edge_pad_ratio (float): Box pad ratio for long edge
            corresponding to font size.
        short_edge_pad_ratio (float): Box pad ratio for short edge
            corresponding to font size.
    """
    assert utils.is_type_list(box, float) or utils.is_type_list(box, int)
    assert len(box) == 8
    assert 0. <= long_edge_pad_ratio < 1.0
    assert 0. <= short_edge_pad_ratio < 1.0

    h, w = src_img.shape[:2]
    points_x = np.clip(np.array(box[0::2]), 0, w)
    points_y = np.clip(np.array(box[1::2]), 0, h)

    box_width = np.max(points_x) - np.min(points_x)
    box_height = np.max(points_y) - np.min(points_y)
    font_size = min(box_height, box_width)

    if box_height < box_width:
        horizontal_pad = long_edge_pad_ratio * font_size
        vertical_pad = short_edge_pad_ratio * font_size
    else:
        horizontal_pad = short_edge_pad_ratio * font_size
        vertical_pad = long_edge_pad_ratio * font_size

    left = np.clip(int(np.min(points_x) - horizontal_pad), 0, w)
    top = np.clip(int(np.min(points_y) - vertical_pad), 0, h)
    right = np.clip(int(np.max(points_x) + horizontal_pad), 0, w)
    bottom = np.clip(int(np.max(points_y) + vertical_pad), 0, h)

    dst_img = src_img[top:bottom, left:right]

    return dst_img




def rotate(
        img,  # 图片
        pt1, pt2, pt3, pt4
):
    # print(pt1,pt2,pt3,pt4)
    widthRect = math.sqrt((pt4[0] - pt1[0]) ** 2 + (pt4[1] - pt1[1]) ** 2)  # 矩形框的宽度
    heightRect = math.sqrt((pt1[0] - pt2[0]) ** 2 + (pt1[1] - pt2[1]) **2)
    # print(widthRect,heightRect)
    angle = acos((pt4[0] - pt1[0]) / widthRect) * (180 / math.pi)  # 矩形框旋转角度
    # print(angle)

    if pt4[1]>pt1[1]:
        angle = angle
        # print("顺时针旋转")
    else:
        # print("逆时针旋转")
        angle=-angle

    height = img.shape[0]  # 原始图像高度
    width = img.shape[1]   # 原始图像宽度
    rotateMat = cv2.getRotationMatrix2D((width / 2, height / 2), angle, 1)  # 按angle角度旋转图像
    heightNew = int(width * fabs(sin(radians(angle))) + height * fabs(cos(radians(angle))))
    widthNew = int(height * fabs(sin(radians(angle))) + width * fabs(cos(radians(angle))))

    rotateMat[0, 2] += (widthNew - width) / 2
    rotateMat[1, 2] += (heightNew - height) / 2
    imgRotation = cv2.warpAffine(img, rotateMat, (widthNew, heightNew), borderValue=(255, 255, 255))
    #print(imgRotation.shape)
    #imgRotation11 = cv2.resize(imgRotation, (800,800))
    #cv2.imshow('rotateImg2',  imgRotation11)
    #cv2.waitKey(0)

    # 旋转后图像的四点坐标
    [[pt1[0]], [pt1[1]]] = np.dot(rotateMat, np.array([[pt1[0]], [pt1[1]], [1]]))
    [[pt3[0]], [pt3[1]]] = np.dot(rotateMat, np.array([[pt3[0]], [pt3[1]], [1]]))
    [[pt2[0]], [pt2[1]]] = np.dot(rotateMat, np.array([[pt2[0]], [pt2[1]], [1]]))
    [[pt4[0]], [pt4[1]]] = np.dot(rotateMat, np.array([[pt4[0]], [pt4[1]], [1]]))

    # 处理反转的情况
    if pt2[1]>pt4[1]:
        pt2[1],pt4[1]=pt4[1],pt2[1]
    if pt1[0]>pt3[0]:
        pt1[0],pt3[0]=pt3[0],pt1[0]
    #print(max(0,int(pt2[1])),int(pt4[1]))
    #print(max(0,int(pt1[0])),int(pt3[0]))
    imgOut = imgRotation[max(0,int(pt2[1])):int(pt4[1]), max(0,int(pt1[0])):int(pt3[0])]
    #print(imgOut.shape)
    # cv2.imshow("imgOut", imgOut)  # 裁减得到的旋转矩形框
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()
    return imgOut  # rotated image


def get_word_pic_acd_box(img, pred_box):
    points = []
    for i in range(int(len(pred_box)/2)):
        points.append([pred_box[i*2+1],pred_box[i*2]])
    points = np.array(points,dtype=np.float32)
    rect = cv2.minAreaRect(points)
    box_origin = cv2.boxPoints(rect)
    m = 0
    for i in range(1, 4):
        if (box_origin[i, 1] + box_origin[i, 0]) < (box_origin[m, 1] + box_origin[m, 0]):
            m = i
    img_cut = rotate(img, [box_origin[m, 1], box_origin[m, 0]], [box_origin[(m+1)%4, 1], box_origin[(m+1)%4, 0]],
                 [box_origin[(m+2)%4, 1], box_origin[(m+2)%4, 0]], [box_origin[(m+3)%4, 1], box_origin[(m+3)%4, 0]])
    return img_cut

def draw_text(img, polys,text_recs, langs):
    blank_pil =Image.new("RGB", Image.fromarray(img).size, (255,255,255))
    blank_draw = ImageDraw.Draw(blank_pil)
    for poly, text,lang in zip(polys,text_recs,langs):
        pt1, pt2, pt3, pt4=poly
        y1=np.max(poly[:,1])
        y0=np.min(poly[:,1])
        x0=np.min(poly[:,0])
        ylength=max(y1-y0,16)
        if len(text) > 0:
            print(text)
            font = ImageFont.truetype('font/%s.ttf'%lang, max(int(ylength * 0.6), 16))
            blank_draw.text(xy=(x0,y0), text=text, font=font,fill=(255,0,0))
    blank_pil=np.array(blank_pil)
    return blank_pil